const useStorage = ($storage: any) => {
  /**
   * 根据 key 值获取储存在 storage 中的值
   * @param key storage key
   */
  const get = (key: string) => {
    const dataStr = $storage.getItem(key)
    try {
      const data = JSON.parse(dataStr)
      const expire = data.expire
      let value = data.value
      if (expire !== 'permanent' && expire > 0 && Date.now() > data.expire) {
        value = ''
        remove(key)
      }
      return value
    } catch {
      return ''
    }
  }

  /**
   * 根据 key 值向 storage 中储存值
   * @param key storage key
   * @param value 需要储存在 storage 中的值
   * @param expire 过期时间 ms数
   */
  const set = (key: string, value: any, expire?: number) => {
    const data = {
      value,
      expire: expire ? Date.now() + expire : 'permanent'
    }
    return $storage.setItem(key, value ? JSON.stringify(data) : value)
  }

  /**
   * 根据 key 值移除储存在 storage 中的值
   * @param key storage key
   */
  const remove = (key: string) => {
    return $storage.removeItem(key)
  }

  /**
   * 移除除了 key 之外的所有储存在 storage 中的值
   * @param key storage key
   */
  const clearExcept = (key: string) => {
    for (let i = 0; i < $storage.length; i++) {
      const itemKey: string | undefined = $storage.key(i)
      if (itemKey && itemKey !== key) {
        $storage.removeItem(itemKey)
      }
    }
  }

  /**
   * 移除所有储存在 storage 中的值
   */
  const clearAll = () => {
    for (const itemKey in $storage) {
      if (itemKey) {
        $storage.removeItem(itemKey)
      }
    }
  }

  return {
    get,
    set,
    remove,
    clearExcept,
    clearAll
  }
}

const SessionStorageService = useStorage(window.sessionStorage || sessionStorage)
const LocalStorageService = useStorage(window.localStorage || localStorage)

export { SessionStorageService, LocalStorageService }
